package com.xcfw.dorm.controller.dormcenter;

import com.xcfw.dorm.config.MyProps;
import com.xcfw.dorm.controller.BaseController;
import com.xcfw.dorm.entity.NumEnum;
import com.xcfw.dorm.entity.ReturnJson;
import com.xcfw.dorm.entity.Student;
import com.xcfw.dorm.exception.ValidationException;
import com.xcfw.dorm.seviceimpl.dormcenter.HandleExcelServiceImpl;
import com.xcfw.dorm.util.DormUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @program: Dorm
 * @description: 导入
 * @author: Bruse Queen
 * @create: 2018-05-04 17:04
 **/
@RestController
@CrossOrigin
@Slf4j
@RequestMapping(value = "/dormcenter")
public class HandleExcelController extends BaseController {

    @Autowired
    private HandleExcelServiceImpl handleExcelService;

    @Autowired
    private DormUtil dormUtil;

    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public ReturnJson importExcel(MultipartFile file) {
        try {
            // 获取图片大小
            long size = file.getSize();
            if (size == 0) {
                // 判断文件内容是否为空
                throw new ValidationException("上传表格不能为空!");
            }
            // 限制图片大小
            if (size > NumEnum.FIVE.getIndex() * NumEnum.MB.getIndex()) {
                throw new ValidationException("请上传表格大小为5MB以下的图片!");
            }
            // 获取文件后缀名
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            if (!".xls".equals(suffix) && !".xlsx".equals(suffix)) {
                throw new ValidationException("表格只能是xls和xlsx!");
            }

            List<Student> list = handleExcelService.readExcel(file, suffix);
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "数据导入成功！", list);
        } catch (ValidationException e) {
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }

    @RequestMapping("/outExcel")
    public ReturnJson outExcel() {
        try {
            result = new ReturnJson(NumEnum.SUCCESS.getIndex(), "表格平面图生成成功！", handleExcelService.outExcel());
        } catch (ValidationException e) {
            result = new ReturnJson(NumEnum.FAIL.getIndex(), e.getMessage());
        }
        return result;
    }
}
